#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#include "../core/config.h"
#include "xbar.h"

static xbar_slave_intf_t xbar_slave_intf[MAX_PERIPS];
static uint8_t slave_register_index;


int xbar_slave_register(xbar_slave_intf_t *slave)
{
    if (slave_register_index >= MAX_PERIPS) {
        printf("%s, perips too much\n", __func__);
        return -1;
    }

    xbar_slave_intf[slave_register_index].start_addr = slave->start_addr;
    xbar_slave_intf[slave_register_index].size = slave->size;
    xbar_slave_intf[slave_register_index].read = slave->read;
    xbar_slave_intf[slave_register_index].write = slave->write;
    slave_register_index++;

    return 0;
}

uint32_t xbar_master_read(uint32_t addr)
{
    uint8_t i;

    for (i = 0; i < slave_register_index; i++) {
        if ((addr >= xbar_slave_intf[i].start_addr) &&
            ((addr + 4) <= (xbar_slave_intf[i].start_addr + xbar_slave_intf[i].size))) {
            return xbar_slave_intf[i].read(addr);
        }
    }

    printf("%s, addr = 0x%x, out of range\n", __func__, addr);
    exit(-1);
    return 0;
}

uint32_t xbar_master_write(uint32_t addr, uint8_t be, uint32_t val)
{
    uint8_t i;

    for (i = 0; i < slave_register_index; i++) {
        if ((addr >= xbar_slave_intf[i].start_addr) &&
            ((addr + 4) <= (xbar_slave_intf[i].start_addr + xbar_slave_intf[i].size))) {
            return xbar_slave_intf[i].write(addr, be, val);
        }
    }

    printf("%s, addr = 0x%x, out of range\n", __func__, addr);
    exit(-1);
    return 0;
}
